﻿using System;
using MediatR;
using Casamiel.Domain.Response;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Domain;
using Newtonsoft.Json;

namespace Casamiel.Application.Commands
{
	public class UnlockCommandHandler : IRequestHandler<UnlockCommand, BaseResult<string>>
	{
		private readonly IHlEmployeeRepository _hlEmployeeRepository;
		private readonly IHLLoginRepository _hLLoginRepository;
		private readonly IMemberAccessTokenRepository _memberAccessTokenRepository;

		/// <summary>
		/// 
		/// 
		/// </summary>
		/// <param name="hlEmployeeRepository"></param>
		/// <param name="hLLoginRepository"></param>
		/// <param name="memberAccessTokenRepository"></param>
		public UnlockCommandHandler(IHlEmployeeRepository hlEmployeeRepository, IHLLoginRepository hLLoginRepository, IMemberAccessTokenRepository memberAccessTokenRepository)
		{
			_hlEmployeeRepository = hlEmployeeRepository;
			_hLLoginRepository = hLLoginRepository;
			_memberAccessTokenRepository = memberAccessTokenRepository;
		}

		public async Task<BaseResult<string>> Handle(UnlockCommand request, CancellationToken cancellationToken)
		{
			if (request == null) {
				throw new ArgumentNullException(nameof(request));
			}
			Console.WriteLine($"{JsonConvert.SerializeObject(request)}");
			var loginentity = await _hLLoginRepository.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
			if (loginentity == null) {
				return new BaseResult<string>("", 9999, "用户信息不存在");
			}

			var password = Common.Utilities.SecurityUtil.EncryptText(request.Password, loginentity.PasswordSalt);
			if (password != loginentity.Password) {
				return new BaseResult<string>("", 9999, "密码不对");
			}
			return new BaseResult<string>("", 0, "操作成功");
		}
	}
	}
